/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.exporters;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.bugstat.common.BugProvider;
import org.bugstat.common.bugs.Bug;

/**
 * This class is used to read back information about bugs. 
 *
 * @author Basil Shikin
 *
 */
public class BugInfoReader
    implements BugProvider
{
    private final File storageLocation;
    
    private final UserReferenceStorage      userStorage;
    private final ComponentReferenceStorage componentStorage;
    private final ProductReferenceStorage   productStorage;

    private final BugTemporalInfoReader  tempReader;
    private final BugPermanentInfoReader permReader;
    
    private final RecordStorage permRecord;
    private final RecordStorage tempRecord;
    
    private File[] temporalFiles = new File[0];
    
    /**
     * Create new bug info reader
     * 
     * @param storageLocation Location of file storage.
     */
    public BugInfoReader(File storageLocation)
    {
        if ( storageLocation == null ) throw new IllegalArgumentException("Invalid storage location specified");
        if ( !storageLocation.exists()) throw new IllegalArgumentException("Invalid storage location specified: " + storageLocation.getAbsolutePath() );
        
        this.storageLocation = storageLocation;
        
        userStorage = new UserReferenceStorage();
        componentStorage = new ComponentReferenceStorage();
        productStorage = new ProductReferenceStorage();
        
        tempRecord = new RecordStorage( BugTemporalInfoWriter.HEADER_LENGTH, BugTemporalInfoWriter.RECORD_LENGTH );
        tempReader = new BugTemporalInfoReader(userStorage, componentStorage, productStorage);
        
        permRecord = new RecordStorage( BugPermanentInfoWriter.HEADER_LENGTH, BugPermanentInfoWriter.RECORD_LENGTH );
        permReader = new BugPermanentInfoReader(permRecord, userStorage);
    }

    public void initializeReader() throws IOException
    {
        final StorageManager storageManager = new StorageManager( storageLocation );
        storageManager.loadReferenceStorage( userStorage );
        storageManager.loadReferenceStorage( componentStorage );
        storageManager.loadReferenceStorage( productStorage );
        
        storageManager.loadPermStorage( permRecord, BugPermanentInfoWriter.PERM_STORAGE_NAME );
        
        temporalFiles = storageManager.listTemporalFiles();
    }

    @Override
    public void retrieveBugs(Date date, BugReceiver reciever) throws IOException
    {
        final File nextFile = StorageManager.nextTemporalFile( temporalFiles, date);
        
        if ( nextFile.exists() )
        {
            tempRecord.loadRecords( nextFile );
            
            iterateOverTempBugs( reciever );
        }
        else
        {
            throw new RuntimeException("Unable to find temporal file for " + date );
        }
    }

    private void iterateOverTempBugs(BugReceiver reciever) throws IOException
    {
        Bug currentBug = new Bug();
        
        for ( int bugID = 1; bugID < tempRecord.size(); bugID++ )
        {
            // Read bug permanent info
            currentBug.setId( bugID );
            currentBug.setCreatedBy( permReader.readCreatedBy( bugID ) );
            currentBug.setCreatedAt( permReader.readCreatedDate(bugID ) );
            
            // Read bug temporal info
            currentBug.setAssignedTo( tempReader.readAssignedTo(bugID, tempRecord) );
            currentBug.setStatus( tempReader.readStatus(bugID, tempRecord) );
            currentBug.setResolution( tempReader.readResolution(bugID, tempRecord) );
            currentBug.setPriority( tempReader.readPriority(bugID, tempRecord) );
            currentBug.setSeverity( tempReader.readSeverity(bugID, tempRecord) );
            currentBug.setPlatform( tempReader.readPlatform(bugID, tempRecord) );
            currentBug.setComponent( tempReader.readComponent(bugID, tempRecord) );
            currentBug.setProduct( tempReader.readProduct(bugID, tempRecord) );
            currentBug.setCommentsNumber( tempReader.readCommentsNumber(bugID, tempRecord) );
            
            reciever.processBug( currentBug );
        }
    }
}
